package com.lgc.common.widget

import android.view.MenuItem
import androidx.core.view.forEachIndexed
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.bottomnavigation.BottomNavigationView

/**
 * 将BottomNavigationView和ViewPager2进行关联以tablayout的方式进行结合
 */
class NavVp2Mediator(private val navView:BottomNavigationView,private val vp2Main:ViewPager2,private val config:(BottomNavigationView,ViewPager2)->Unit) {
    private val map:MutableMap<MenuItem,Int> = mutableMapOf<MenuItem,Int>()
    init {
        navView.menu.forEachIndexed { index, item ->
            map[item]=index
        }
    }

    /**
     * 将BottomNavigationView和ViewPager2进行关联
     */
    fun attach(){
        config.invoke(navView,vp2Main)
        //ViewPager2的滑动页面监听
        vp2Main.registerOnPageChangeCallback(object:ViewPager2.OnPageChangeCallback(){
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                navView.selectedItemId=navView.menu.getItem(position).itemId
            }
        })

        //用于监听并响应底部导航图BottomNavigationView中的菜单项的选中事件，当用户点击不同按钮时会被触发
        navView.setOnItemSelectedListener{ item ->
            vp2Main.currentItem = map[item]!! ?: error("未找到对应的索引位置")
            true
        }
    }
}